package com.car.account.util.aliyunUtil;

import cn.hutool.core.io.FileTypeUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.car.account.exception.AccountException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
@Data
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssUtil {
    //节点域名
    private String host;
    //账号的身份ID
    private String accessId;
    //账号的身份凭证
    private String accessSecret;
    /**
     * 上传文件
     * @param file 文件数据
     * @param name 文件名
     * @param bucketName 存储空间名
     * @return 文件的访问地址
     */
    public String uploadFile(InputStream file, String name, String bucketName) {
        //创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //上传
            ossClient.putObject(bucketName, name, file);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return "https://" + bucketName + "."+ host + "/"+name;
    }
    /**
     * 删除文件
     * @param bucketName 存储空间名
     * @param name 文件名
     * @return
     */
    public boolean deleteFile(String bucketName,String name) {
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //删除文件
            ossClient.deleteObject(bucketName, name);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return true;
    }

    public String upImage(MultipartFile image) throws Exception {
        //文件上传
        String type = FileTypeUtil.getType(image.getInputStream());
        if (!"jpg".equals(type)&&!"png".equals(type)){
            throw new AccountException(5000,"图片类型错误");
        }
        //获取文件名
        String name = image.getOriginalFilename();
        //获取文件的后缀名
        String suffix = name.substring(name.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;
        String imgUrl = uploadFile(image.getInputStream(), fileName, "superman-book");
        return imgUrl;
    }

}
